import React, { useState, useEffect } from "react"
import axios from "axios"

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
export const withEditableResouce = (Component, resourcePath, resourceName) => {
    return props => {
        const [originalData, setOriginalData] = useState(null);
        const [data, setData] = useState(null);

        useEffect(() => {
            (async () => {
                const response = await axios.get(resourcePath)
                setOriginalData(response.data);
                setData(response.data);
            })()
        }, [])

        // oncChange
        const onChange = changes => {
            setData({ ...data, ...changes });
        }

        // onReset
        const onReset = () => {
            setData(originalData);
        }

        const onSave = async () => {
            const response = await axios.post(resourcePath, data);
            setData(response.data);
            setOriginalData(response.data);
        }

        const resourceProps = {
            [resourceName]: data,
            [`onChange${capitalize(resourceName)}`]: onChange,
            [`onReset${capitalize(resourceName)}`]: onReset,
            [`onSave${capitalize(resourceName)}`]: onSave,
        }
        return <Component {...props} {...resourceProps} ></Component>
    }
}